import Vue from 'vue'
import md5 from 'js-md5'

const user = {
  state: {
    token: '',
    self: {},
    role: {},
    name: '',
    avatar: '',
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLE: (state, role) => {
      state.role = role
    },
    SET_SELF: (state, self) => {
      state.self = self
    }
  },

  actions: {
    // 获取接入token
    fetchToken({ commit }) {
      let token = user.state.token
      let userId = user.state.userId
      if (token == null || token.length === 0) {
        token = Vue.prototype.getLocalStorage('token')
      }
      if (userId == null || userId.length === 0) {
        userId = Vue.prototype.getLocalStorage('operator')
      }
      return new Promise((resolve, reject) => {
        if (token == null || token.length === 0) {
          Vue.prototype.fetch(Vue.prototype.apiType.common.getToken, null, null,
            respData => {
              commit('SET_TOKEN', respData.data.token)
              resolve(respData.data.token)
            })
        } else {
          Vue.prototype.fetch(Vue.prototype.apiType.common.verifyToken,
            {
              token: token,
              userId: userId
            },
            null,
            respData => {
              if (respData.data) {
                commit('SET_TOKEN', token)
                resolve(token)
              } else {
                Vue.prototype.fetch(Vue.prototype.apiType.common.getToken, null, null,
                  respData => {
                    commit('SET_TOKEN', respData.data.token)
                    resolve(respData.data.token)
                  }, errData => {
                    reject(errData)
                  })
              }
            }, errData => {
              Vue.prototype.fetch(Vue.prototype.apiType.common.getToken, null, null,
                respData => {
                  commit('SET_TOKEN', respData.data.token)
                  resolve(respData.data.token)
                }, errData => {
                  reject(errData)
                })
            })
        }
      })
    },
    // 登录
    login({ commit }, userInfo) {
      userInfo.password = md5(userInfo.password)
      return new Promise((resolve, reject) => {
        Vue.prototype.fetch(Vue.prototype.apiType.login.passwordLogin, userInfo, null,
          respData => {
            commit('SET_TOKEN', respData.data.accessToken)
            commit('SET_NAME', respData.data.userId)
            commit('SET_AVATAR', respData.data.name)
            resolve(respData)
          }, errData => {
            reject(errData)
          })
      })
    },
    // 短信验证码登录
    msgCodeLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        Vue.prototype.fetch(Vue.prototype.apiType.login.msgCodeLogin, userInfo, null,
          respData => {
            commit('SET_TOKEN', respData.data.accessToken)
            commit('SET_NAME', respData.data.userId)
            commit('SET_AVATAR', respData.data.name)
            resolve(respData)
          }, errData => {
            reject(errData)
          })
      })
    },
    // 获取用户信息
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        Vue.prototype.fetch(Vue.prototype.apiType.userInfo.getUserInfo, null, null,
          respData => {
            commit('SET_SELF', respData.data)
            resolve(respData.data)
          }, err => {
            reject(err)
          })
      })
    },

    getRoleInfo({ commit }) {
      return new Promise((resolve, reject) => {
        Vue.prototype.fetch(Vue.prototype.apiType.userInfo.getRoleInfo, null, null,
          respData => {
            commit('SET_ROLE', respData.data)
            resolve(respData.data)
          }, err => {
            reject(err)
          })
      })
    },
    updateUserInfo({ commit }, userInfo) {
      userInfo.password = md5(userInfo.password)
      userInfo.passwordConfirm = md5(userInfo.passwordConfirm)
      return new Promise((resolve, reject) => {
        Vue.prototype.fetch(Vue.prototype.apiType.userInfo.updateUserInfo, null, userInfo,
          respData => {
            resolve(respData.data)
          }, err => {
            reject(err)
          })
      })
    },
    ssoLogin({ commit }, token) {
      const ssoToken = {
        token: token
      }
      return new Promise((resolve, reject) => {
        Vue.prototype.fetch(Vue.prototype.apiType.ssoLogin, ssoToken, null,
          respData => {
            commit('SET_NAME', respData.data.userName)
            commit('SET_AVATAR', respData.data.name)
            if (respData.data.token) {
              commit('SET_TOKEN', respData.data.token)
              resolve(respData)
            } else {
              reject(respData.data.token)
            }
          }, errData => {
            reject(errData)
          }, null, false)
      })
    },

    thirdPartyLogin({ commit }, urlLoginParam) {
      return new Promise((resolve, reject) => {
        if (Vue.prototype.isNotEmpty(urlLoginParam.token) && Vue.prototype.isNotEmpty(urlLoginParam.userId)) {
          Vue.prototype.setLocalStorage('loginMode', '1')
          commit('SET_TOKEN', urlLoginParam.token)
          commit('SET_NAME', urlLoginParam.userId)
          Vue.prototype.setLocalStorage('token', urlLoginParam.token)
          Vue.prototype.setLocalStorage('operator', urlLoginParam.userId)

          resolve()
        } else if (Vue.prototype.isNotEmpty(urlLoginParam.appId) && Vue.prototype.isNotEmpty(urlLoginParam.timeStamp) &&
          Vue.prototype.isNotEmpty(urlLoginParam.nonce) && Vue.prototype.isNotEmpty(urlLoginParam.signature) &&
          Vue.prototype.isNotEmpty(urlLoginParam.userId) && Vue.prototype.isNotEmpty(urlLoginParam.userName)) {
          Vue.prototype.setLocalStorage('loginMode', '2')
          Vue.prototype.fetch(Vue.prototype.apiType.login.thirdPartyLogin, urlLoginParam, null,
            respData => {
              commit('SET_TOKEN', respData.data.accessToken)
              commit('SET_NAME', respData.data.userId)
              commit('SET_AVATAR', respData.data.name)
              resolve(respData.data)
            }, errData => {
              reject(errData)
            }, true, false)
        } else {
          reject(urlLoginParam)
        }
      })
    },

    // 登出
    logOff({ commit }) {
      return new Promise((resolve, reject) => {
        Vue.prototype.fetch(Vue.prototype.apiType.login.logoff, null, null,
          respData => {
            commit('SET_TOKEN', '')
            commit('SET_NAME', '')
            commit('SET_AVATAR', '')
            commit('SET_SELF', {})
            commit('SET_ROLE', {})

            resolve(respData)
          }, errData => {
            reject(errData)
          })
      })
    },

    refreshLogin({ commit }) {
      const param = {
        refreshToken: Vue.prototype.getLocalStorage('refreshToken')
      }
      return new Promise((resolve, reject) => {
        Vue.prototype.fetch(Vue.prototype.apiType.login.refreshLogin, param, null,
          respData => {
            commit('SET_TOKEN', respData.data.accessToken)
            commit('SET_NAME', respData.data.userId)
            commit('SET_AVATAR', respData.data.name)
            resolve(respData)
          }, errData => {
            reject(errData)
          })
      })
    },

    // 前端 登出
    fedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_NAME', '')
        commit('SET_AVATAR', '')
        resolve()
      })
    }
  }
}

export default user
